<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applicant">
            <UserSelect v-model="form.applicant" :placeholder="$t('申请人')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applicationTime">
            <el-date-picker
              v-model="form.applicationTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请部门')" prop="deptId">
            <tree-select
              v-model="form.deptId"
              :default-expand-all="true"
              :data="initData.deptOptions"
              node-key="id"
              :placeholder="$t('请选择')"
              disabled
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系电话')" prop="phone">
            <el-input v-model="form.phone" :placeholder="$t('联系电话')" show-word-limit maxlength="11" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="$t('选择需要销假的休假申请标题')" prop="vacationActTitle">
            <el-input v-model="form.vacationActTitle" readonly :placeholder="$t('选择需要销假的休假申请标题')" show-word-limit :maxlength="100">
              <template slot="append" icon="el-icon-search">
                <el-button
                  v-if="!isW"
                  v-hasPermi="['oa:vacation:edit']"
                  type="primary"
                  icon=""
                  size="mini"
                  @click="showVacation"
                >
                  {{ $t('查询休假信息') }}
                </el-button>
                <el-button
                  v-else
                  v-hasPermi="['oa:vacation:edit']"
                  type="primary"
                  icon=""
                  size="mini"
                  @click="showVacationInfo"
                >
                  {{ $t('查看休假信息') }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('休假时间')" prop="startDate">
            <DatePicker
              v-model="dateRange"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              @change="vacationDays"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('实际申请天数')" prop="vacationDay">
            <el-input v-model="form.vacationDay" :placeholder="$t('申请休假天数')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('工作交接人')" prop="workUser">
            <UserSelect v-model="form.workUser" :placeholder="$t('工作交接人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('去除节假日休假天数')" prop="removeHoliday">
            <el-input v-model="form.removeHoliday" :placeholder="$t('去除节假日休假天数')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('通知人员')" prop="noticeUsers">
            <UserSelect v-model="form.noticeUsers" multiple :placeholder="$t('通知人员')" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('休假明细') }}</span>
      </div>
      <el-table :data="form.oaVacationDetails" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('申请休假类型')" align="center" prop="vacationType">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('申请休假类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'oaVacationDetails.' + scope.$index + '.vacationType'"
            >
              <el-select v-model="scope.row.vacationType" disabled>
                <el-option
                  v-for="(ele, index) in initData.vacationTypeOptions"
                  :key="index"
                  :value="ele.id"
                  :label="$t(ele.type)"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('实际剩余天数')" align="center" prop="remainDay">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remainDay" disabled />
          </template>
        </el-table-column>
        <el-table-column :label="$t('本次申请天数')" align="center" prop="vacationDay">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('本次申请天数') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaVacationDetails.' + scope.$index + '.vacationDay'">
              <el-input-number
                v-model="scope.row.vacationDay"
                :controls="false"
                :precision="1"
                :placeholder="$t('本次申请天数')"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('本次实际天数')" align="center" prop="actualVacationDay">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('本次实际天数') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaVacationDetails.' + scope.$index + '.actualVacationDay'" :rules="detailsRules.actualVacationDay">
              <el-input-number
                v-model="scope.row.actualVacationDay"
                :controls="false"
                :precision="1"
                :placeholder="$t('本次实际天数')"
                @blur="actualVacationDayChange(scope.row)"
              />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>

      <FileTable :list.sync="form.fileList" data-type="oa_leave" :btn-show="!otherBtnHide" />
    </el-form>

    <!-- 按钮 -->
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:leaveOff" :menu-key="menuKey" />
    </div>
    <el-dialog
      :title="$t('休假列表')"
      :visible.sync="formOpen"
      custom-class="fixedDialog"
      width="70%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <oaVacationList ref="oaVacationList" />
    </el-dialog>

    <el-dialog
      :title="$t('休假详情')"
      :visible.sync="actOpen"
      custom-class="fixedDialog"
      width="70%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <ProcessInfoForm ref="processInfoForm" />
    </el-dialog>
  </div>
</template>

<script>
import { saveOaLeaveOff, getOaLeaveOff } from '@/api/oa/leave/oaLeaveOff'
import { countSurplusDay, getOaVacation } from '@/api/oa/vacation/vacation/oaVacation'
import { getUser } from '@/api/system/user'
import TreeSelect from '@/components/TreeSelect'
import { treeselect } from '@/api/system/dept'
import { findAll } from '@/api/oa/vacation/type/oaVacationType'
import oaVacationList from './oaVacationList.vue'
import ProcessInfoForm from '@/views/act/process/processInfoForm'

export default {
  components: { TreeSelect, oaVacationList, ProcessInfoForm },
  data() {
    return {
      // 菜单标识
      menuKey: this.$t('oa_leave'),
      formOpen: false,
      actOpen: false,
      dateRange: [],
      // 表单参数
      form: {
        fileList: []
      },
      // 表单校验
      rules: {
        applicant: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], applicationTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], actTitle: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], vacationActTitle: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      detailsRules: {
        actualVacationDay: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      otherBtnHide: false,
      initData: {
        oaVacations: [],
        deptOptions: [],
        // 休假类型
        vacationTypeOptions: []
      },
      deptId: undefined,
      vacationData: {},
      isVacation: false,
      vacationId: undefined,
      isW: false
    }
  },
  created() {
    this.initDataMethod()
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      // 查询销假数据
      if (data != null && data.id !== undefined) {
        this.isW = true
        getOaLeaveOff(data.id).then(response => {
          this.form = response.data
          this.vacationId = response.data.vacationId
          this.$set(this.dateRange, 0, response.data.startDate)
          this.$set(this.dateRange, 1, response.data.endDate)
        })
      } else {
        this.isW = false
        this.reset()
        this.vacationId = undefined
      }
      this.loading = false
    },
    // 表单重置
    reset() {
      const userId = this.$store.state.user.userId
      this.form = {
        id: undefined,
        applicant: userId,
        applicationTime: new Date(),
        phone: undefined,
        startDate: undefined,
        endDate: undefined,
        vacationDay: undefined,
        removeHoliday: undefined,
        workUser: undefined,
        noticeUsers: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        actId: undefined,
        actStatus: undefined,
        actTitle: undefined,
        vacationId: undefined
      }
      this.resetForm('form')
      getUser(userId).then(res => {
        this.$set(this.form, 'deptId', res.data.deptId)
        this.$set(this.form, 'phone', res.data.phonenumber)
      })
      this.applicationTime = new Date()
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    // 提交按钮
    submitForm: function(type) {
      if (this.form.oaVacationDetails === undefined || this.form.oaVacationDetails.length === 0) {
        this.msgError(this.$t('休假天数和去除节假日总天数不相等'))
        return
      }
      let totalDay = 0
      for (let i = 0; i < this.form.oaVacationDetails.length; i++) {
        if (!this.actualVacationDayChange(this.form.oaVacationDetails[i])) {
          return
        }
        totalDay += Number(this.form.oaVacationDetails[i].actualVacationDay)
      }
      if (totalDay !== Number(this.form.removeHoliday)) {
        this.msgError(this.$t('实际休假天数和去除节假日总天数不相等'))
        return
      }

      this.$refs['form'].validate(valid => {
        // 验证数据
        if (valid) {
          // 弹出遮罩层
          this.loading = true
          if (this.dateRange && this.dateRange.length > 0) {
            this.form.startDate = this.dateRange[0] + ':00'
            this.form.endDate = this.dateRange[1] + ':00'
          }
          // 保存数据
          saveOaLeaveOff(this.form).then(response => {
            if (response.code === 200) {
              // 点击的按钮是保存并启动流程
              if (type === 'process') {
                // 启动流程
                this.startProcess(response.data)
                // 点击的仅保存
              } else {
                this.msgSuccess(this.$t('保存成功'))
                // 关闭form页面
                this.closeForm()
              }
            } else {
              this.msgError(response.msg)
              this.loading = false
            }
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = dataId.actTitle
      // 业务表名
      processData.dataTable = 'oa_leave_off'
      // 业务ID
      processData.dataId = dataId.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/leave/oaLeaveOffForm'
      processData.viewPath = '@/views/oa/leave/oaLeaveOffView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 计算时间
    vacationDays(val) {
      if (val === null || val === undefined || val === '') {
        this.form.vacationDay = ''
        this.form.removeHoliday = ''
      } else {
        const date = {
          startDate: val[0] + ':00',
          endDate: val[1] + ':00'
        }
        countSurplusDay(date).then(response => {
          this.form.vacationDay = response.data.totalDay
          this.form.removeHoliday = response.data.surplusDay
        })
      }
    },
    // 初始化数据
    initDataMethod() {
      treeselect().then(response => {
        this.initData.deptOptions = response.data
      })
      findAll().then(response => {
        this.initData.vacationTypeOptions = response.data
      })
    },
    // 显示 休假详情
    showVacation() {
      this.formOpen = true
      this.$nextTick(() => {
        this.$refs.oaVacationList.getList(this.vacationId)
      })
    },
    // 流程完成 查看休假信息 点击直接查看详情
    showVacationInfo() {
      this.actOpen = true
      this.$nextTick(() => {
        if (this.vacationId === null || this.vacationId === undefined) {
          this.$message.error(this.$t('未保存，无法查看流程'))
          return
        }

        getOaVacation(this.vacationId).then(res => {
          const proData = {}
          proData.actId = res.data.actId
          this.$refs.processInfoForm.init(proData)
        })
      })
    },
    // 选择 休假数据回显
    getOaVacationData(data) {
      this.$set(this.form, 'vacationId', data.id)
      this.$set(this.form, 'vacationActTitle', data.actTitle)
      // 回显数据
      this.vacationData = data
      this.form.vacationDay = data.vacationDay
      this.form.removeHoliday = data.removeHoliday
      this.form.oaVacationDetails = data.oaVacationDetails
      // for (let i = 0; i < data.oaVacationDetails.length; i++) {
      //   this.$set(this.form.oaVacationDetails[i], 'actualVacationDay', data.oaVacationDetails[i].vacationDay)
      // }
      this.$set(this.form, 'workUser', data.workUser)
      this.$set(this.form, 'noticeUsers', data.noticeUsers)
      this.dateRange = [data.startDate, data.endDate]
      if (data.id !== undefined && data.id !== '') {
        getOaVacation(data.id).then(res => {
          this.$set(this.form, 'fileList', res.data.fileList)
        })
      }
    },
    // 校验实际假期
    actualVacationDayChange(row) {
      if (row.actualVacationDay < 0) {
        this.msgError(this.$t('实际休假天数不能为负数'))
        return false
      } else {
        if (row.actualVacationDay > row.remainDay) {
          this.msgError(this.$t('实际休假天数不能超过剩余天数'))
          return false
        } else {
          return true
        }
      }
    }

  }

}
</script>
